/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedVertexData, pickedModelData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';
import { previewer } from '@app-cad/module';
import { RJSFSchema } from '@rjsf/utils';
import { FeatureBaseCommand, FeaturedCmdDialogParams } from '@app-cad/types';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useMemo, useState } from 'react';

enum SphereMode {
  WHOLE = 'whole',
  PARTIAL = 'partial',
}

type FormData = {
  mode: SphereMode;
  point: pickedVertexData;
  frame?: pickedModelData;
  latitudeS: number;
  latitudeE: number;
  longitudeS: number;
  longitudeE: number;
  radius: number;
};

type Params = {
  mode: SphereMode;
  point: string;
  frame?: string;
  latitudeS: number;
  latitudeE: number;
  longitudeS: number;
  longitudeE: number;
  radius: number;
};

// 圆柱面
function SphereSurface({ title, onClose, props }: FeaturedCmdDialogParams) {
  const initData = {
    mode: SphereMode.WHOLE,
    point: null,
    frame: null,
    latitudeS: -90,
    latitudeE: 90,
    longitudeS: -45,
    longitudeE: 45,
    radius: 20,
  };
  const [formData, setFormData] = useState<FormData>(initData);

  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params: Params = props.params;
    const {
      radius,
      point,
      frame,
      latitudeS,
      latitudeE,
      longitudeS,
      longitudeE,
      mode,
    } = params;

    await initEditDependency([point, frame]);

    setFormData({
      mode: mode,
      point: picker.generatePickObjByPickID(point) as pickedVertexData,
      frame: picker.generatePickObjByPickID(frame) as pickedModelData,
      radius: radius,
      latitudeS: latitudeS,
      latitudeE: latitudeE,
      longitudeS: longitudeS,
      longitudeE: longitudeE,
    });
  }, []);

  useAsyncEffect(async () => {
    previewer.clear();
    if (!isFormDataValid()) {
      return;
    }
    await execute(true);
  }, [formData]);

  const isFormDataValid = () => {
    const { radius, point, latitudeS, latitudeE, longitudeS, longitudeE } =
      formData;

    return (
      point !== null &&
      radius > 0 &&
      latitudeS >= -90 &&
      latitudeE <= 90 &&
      latitudeS < latitudeE &&
      longitudeS < longitudeE
    );
  };
  const finishValid = useMemo(isFormDataValid, [formData]);
  const checkAndFinish = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const { initEditDependency, confirmCommand } = useCommand(
    'cmd-sphere-surface',
    {
      commandName: 'CreateSurface',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinish,
    },
  );

  const execute = async (preview: boolean = false) => {
    const {
      radius,
      point,
      frame,
      latitudeS,
      latitudeE,
      longitudeS,
      longitudeE,
      mode,
    } = formData;
    const params: Params = frame
      ? {
          mode: mode,
          point: getIdOfPickedObj(point),
          frame: getIdOfPickedObj(frame),
          latitudeS: latitudeS,
          latitudeE: latitudeE,
          longitudeS: longitudeS,
          longitudeE: longitudeE,
          radius: radius,
        }
      : {
          mode: mode,
          point: getIdOfPickedObj(point),
          latitudeS: latitudeS,
          latitudeE: latitudeE,
          longitudeS: longitudeS,
          longitudeE: longitudeE,
          radius: radius,
        };
    return confirmCommand(
      {
        type: 'Spherical',
        a: params,
      },
      preview,
    );
  };

  const schema: RJSFSchema = useMemo(() => {
    const axes =
      formData.mode === SphereMode.WHOLE
        ? {}
        : {
            latitudeS: {
              type: 'number',
              title: '最小经度',
              format: NumberInputFormat.Angle,
            },
            latitudeE: {
              type: 'number',
              title: '最大经度',
              format: NumberInputFormat.Angle,
            },
            longitudeS: {
              type: 'number',
              title: '最小纬度',
              format: NumberInputFormat.Angle,
            },
            longitudeE: {
              type: 'number',
              title: '最大纬度',
              format: NumberInputFormat.Angle,
            },
          };

    return {
      type: 'object',
      properties: {
        mode: {
          type: 'string',
          default: SphereMode.WHOLE,
          title: '球面类型',
          oneOf: [
            {
              title: '整体',
              const: SphereMode.WHOLE,
            },
            {
              title: '部分',
              const: SphereMode.PARTIAL,
            },
          ],
        },
        point: {
          type: 'string',
          format: PickInputRJSFFormat.PickVertex,
        },
        frame: {
          type: 'string',
          format: PickInputRJSFFormat.PickFrame,
        },
        radius: {
          type: 'number',
          title: '半径',
          format: NumberInputFormat.Length,
        },
        ...axes,
      },
    } as RJSFSchema;
  }, [formData]);

  return (
    <PickableCommandForm
      isFormDataValid={finishValid}
      disabled={false}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        point: {
          'ui:placeholder': '请输入圆心',
          'ui:autofocus': true,
        },
        frame: {
          'ui:placeholder': '请输入坐标系(可选)',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinish}
    />
  );
}

export const cmdSphereSurface: FeatureBaseCommand = {
  id: 'CmdSphereSurface',
  label: 'command.sphere-surface',
  icon: 'commands/feature/sphere-surface',
  create: (label, onClose, props) => (
    <SphereSurface
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
